package com.ruan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruan.common.Code;
import com.ruan.common.Result;
import com.ruan.mapper.EmployeeMapper;
import com.ruan.mapper.OnDutyMapper;
import com.ruan.pojo.*;
import com.ruan.pojoExt.DepartmentExt;
import com.ruan.pojoExt.OnDutyDTOExt;
import com.ruan.service.*;

import com.ruan.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/onDuty")

public class OnDutyController {

    @Autowired
    private OnDutyService onDutyService;

    @Autowired
    private OnDutySetService onDutySetService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private OnDutyMapper onDutyMapper;

    @Autowired
    PositionService positionService;


    /**
     * 分页条件查询上月份的出勤数据列表
     * @param currentPage 当前页
     * @param pageSize 每页最大数
     * @param ltoQueryCondition 查询条件
     * @return
     */
    @PostMapping("/selectOnDutyDTO/{currentPage}/{pageSize}")
    public Result selectOnDutyDTO(@PathVariable int currentPage,
                                           @PathVariable int pageSize,
                                           @RequestBody LTOQueryCondition ltoQueryCondition) {
//        System.out.println("selectOnDutyDTO的参数是"+ltoQueryCondition);

        Date month = ltoQueryCondition.getMonth();//2024-2-1
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-01");
        String firstDay = sdf.format(month);
//        System.out.println("每月第一天------"+firstDay);
        String lastDay = DateUtils.getLastDay(firstDay);//每月最后一天

        LambdaQueryWrapper<OnDuty> queryWrapper =new LambdaQueryWrapper<>();
        //根据员工名进行搜索
        LambdaQueryWrapper<Employee> queryWrapper1 =new LambdaQueryWrapper<>();
        queryWrapper1.like(Employee::getName,ltoQueryCondition.getName());
        List<Employee> employeeList = employeeMapper.selectList(queryWrapper1);
        List<Long> employeeIds = employeeList.stream().map(Employee::getId).collect(Collectors.toList());
//        wrapper.in("employee_id", employeeIds);//是QueryWrapper的技术语句
        queryWrapper.in(OnDuty::getEmployeeId, employeeIds);
        //根据部门进行搜索
        queryWrapper.eq(ltoQueryCondition.getDepartmentId()!=null,OnDuty::getDepartmentId,ltoQueryCondition.getDepartmentId());
        //搜索这一个月的出勤记录(默认会传来上个月。。)
        queryWrapper.between(OnDuty::getDay,firstDay,lastDay);
        //将具有相同employeeId值的记录分在一组。
        queryWrapper.groupBy(OnDuty::getEmployeeId);

        //排除待审核的员工
        LambdaQueryWrapper<Employee> queryWrapper3 =new LambdaQueryWrapper<>();
        queryWrapper3.eq(Employee::getStatus,"待审核");
        List<Employee> employeeList1 = employeeMapper.selectList(queryWrapper3);
        List<Long> employeeIds1 = employeeList1.stream().map(Employee::getId).collect(Collectors.toList());

        queryWrapper.notIn(OnDuty::getEmployeeId,employeeIds1);

        Page<OnDuty> iPage = new Page<>(currentPage,pageSize);
        Page<OnDutyDTO> iPageExt=new Page<>();//封装

        onDutyMapper.selectPage(iPage, queryWrapper);

        BeanUtils.copyProperties(iPage,iPageExt,"records");//从iPage一个一个拷贝属性到iPageExt上(除了records)
        List<OnDuty> onDuties = iPage.getRecords();//所有员工的出勤记录

//        List<OnDutyDTO> onDutyDTOList = new ArrayList<>();
        List<OnDutyDTO> onDutyDTOList = onDuties.stream().map((onDuty) -> {//item:遍历出来的每一个项目对象
//        for (OnDuty onDuty : onDuties) {//遍历每个员工的出勤状态
            OnDutyDTO onDutyDTO = new OnDutyDTO();
            System.out.println("onDuty是："+onDuty);
            Long employeeId = onDuty.getEmployeeId();
//            List<String> status = onDutyMapper.selectStatus(employeeId,firstDay,lastDay);
            LambdaQueryWrapper<OnDuty> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(OnDuty::getEmployeeId,employeeId);
            List<OnDuty> onDutys = onDutyMapper.selectList(queryWrapper2);
            List<StatusExt> statusExtList = new ArrayList<>();//只包含两个属性(day和status)
            for(OnDuty onDuty1 : onDutys){//单个人的所有天数的出勤记录

            String status = onDuty1.getStatus();

            System.out.println("status1是：" + status);

            StatusExt statusExt = new StatusExt();

            statusExt.setStatus(status);//出勤状态
            statusExt.setDay(onDuty1.getDay());//哪天的出勤状态//用于前端的比对填充

            statusExtList.add(statusExt);//塞入这个属性里保存起来，以便于在页面展示

            System.out.println("statusExt是"+statusExt);

           }

            onDutyDTO.setStatusExt(statusExtList);

            BeanUtils.copyProperties(onDuty,onDutyDTO);
            System.out.println("onDutyDTO属性迁移完成了吗："+onDutyDTO);

            Department department = departmentService.getById(onDuty.getDepartmentId());
            Employee employee = employeeMapper.selectById(onDuty.getEmployeeId());

            onDutyDTO.setStatus(employee.getStatus());//在职？离职？？
            onDutyDTO.setPhone(employee.getPhone());
            onDutyDTO.setEmployeeName(employee.getName());
            Position position = positionService.getById(employee.getPositionId());
            onDutyDTO.setPosition(position.getPname());
            onDutyDTO.setDepartmentName(department.getName());


            return onDutyDTO;
        }).collect(Collectors.toList());
//        onDutyDTOList.setTotal(iPage.getTotal());//查到的出勤记录条数？？
//        System.out.println(onDutyDTOList);
        iPageExt.setRecords(onDutyDTOList);
        return new Result(Code.SELECT_OK,iPageExt);
    }

    @GetMapping("/getOnDutySet")
    public Result getOnDutySet(){

        try {
            OnDutySet onDutySet = onDutySetService.getOnDutySet();
            return new Result(Code.SELECT_OK,onDutySet);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.SELECT_ERR,"出勤时间查询失败");
        }
    }

    @PutMapping("/setOnDuty")
    public Result setOnDuty(@RequestBody OnDutySet onDutySet){

        System.out.println("onDutySet::"+onDutySet);

        try {
            onDutySetService.updateById(onDutySet);
            return new Result(Code.UPDATE_OK,"设置成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.UPDATE_ERR,"出勤时间设置失败！");
        }
    }

    @GetMapping("/getOnDutyStartTime")
    public Result getOnDutyStartTime(){
        OnDutySet onDutySet = onDutySetService.getById(1);
        if (onDutySet!=null){
            return new Result(Code.SELECT_OK,onDutySet.getEndTime());
        }else {
            return new Result(Code.SELECT_ERR,"获取上班时间失败！");
        }

    }

    @GetMapping("/getOnDutyStatus")
    public Result getOnDutyStatus(String phone){

        return onDutyService.getOnDutyStatus(phone);
    }

//    后端报错"Required request body is missing"
//    表明后端期望接收一个请求体，但实际上请求体是空的。
//    可能的原因是axios.post方法的第二个参数应该是请求体数据，
//    而不是this.locationObject和this.basicProp两个对象。
//    将这两个对象合并为一个对象，然后作为请求体发送给后端。
//public Result punchIn(@RequestBody Location location,
//                      @RequestBody OnDuty onDuty){

    @PostMapping("/punchIn")//requestBody
    public Result punchIn(@RequestBody PunchInRequestBody requestBody){
        System.out.println("打卡onDuty传来的是"+requestBody);
        return onDutyService.punchIn(requestBody);
//        return onDutyService.punchIn(location,onDuty);
    }

    @PostMapping("/punchOut")
    public Result punchOut(@RequestParam String phone,
                           @RequestBody Location location){

        return onDutyService.punchOut(phone,location);
    }

    @PostMapping("/getSelfOnDuty/{currentPage}/{pageSize}")
    public Result getSelfOnDuty(@PathVariable int currentPage,
                                @PathVariable int pageSize,
                                @RequestBody QuerySelfAttendanceCondition querySelfAttendanceCondition){
        IPage<OnDuty> iPage = onDutyService.getSelfOnDuty(currentPage,pageSize, querySelfAttendanceCondition);

        if (iPage!=null){
            return new Result(Code.SELECT_OK,iPage);
        }
        return new Result(Code.SELECT_ERR,"查询详细请假信息失败！");
    }

    @PutMapping("/setOnDutyStatus")
    public Result setOnDutyStatus(String phone,String day,String status){
        return onDutyService.setOnDutyStatus(phone,day,status);
    }
}
